package com.kfm.dingtalk.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.kfm.dingtalk.service.ChatService;
import com.kfm.dingtalk.service.DingTalkService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    @Resource
    private ChatService chatService;

    @Resource
    private DingTalkService dingTalkService;


    @PostMapping("/ask")
    public void ask(@RequestBody String payload) {
        String question = JSONUtil.parseObj(payload).getJSONObject("text").getStr("content");
        log.info("question: {}", question);
        String answer = chatService.ask(question);
        log.info("answer: {}", answer);
        try {
            dingTalkService.sendMessage("chat回复\n" + answer);
        } catch (IOException e) {
            log.error("send message error", e);
            throw new RuntimeException(e);
        }
    }
}
